package sqlTest.android;



import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
 
import java.util.ArrayList;
import java.util.List;
 
public class DataHelper {
 
   private static final String DATABASE_NAME = "HOOPLA.db";
   private static final int DATABASE_VERSION = 1;
   private static final String TABLE_NAME = "billetter";
 
   private Context context;
   private SQLiteDatabase db;
 
   private SQLiteStatement insertStmt;
   private SQLiteStatement updateStmt;
   private static final String INSERT = "insert into "
      + TABLE_NAME + "(billettID, scanned) values (?, 'false')";
 
   private static final String UPDATESTATUS = "update "
   + TABLE_NAME + " set scanned = 'true' where billettID = ?";
   
   public DataHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
      this.updateStmt = this.db.compileStatement(UPDATESTATUS);
   }
   
   
   public long updateIsScanned(String ticketID){
	   //db.execSQL("update " + TABLE_NAME + " set scanned = 'true' where billettID = " + "'" + ticketID + "'");
	   this.updateStmt.bindString(1, ticketID);
	   return this.updateStmt.executeInsert();
   }
   
 
   public long insert(String billetID) {
      this.insertStmt.bindString(1, billetID);
      return this.insertStmt.executeInsert();
   }
 
   public void deleteAll() {
      this.db.delete(TABLE_NAME, null, null);
   }
 
   public List<String> selectAll() {
      List<String> list = new ArrayList<String>();
      Cursor cursor = this.db.query(TABLE_NAME, new String[] { "billettID", "scanned"},
        null, null, null, null, null);
      
      if (cursor.moveToFirst()) {
         do {
            list.add(cursor.getString(0));
            list.add(cursor.getString(1));
         } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }
      return list;
   }
 
   private static class OpenHelper extends SQLiteOpenHelper {
 
      OpenHelper(Context context) {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
 
      @Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, billettID TEXT, scanned TEXT)");
      }
 
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         Log.w("Example", "Upgrading database, this will drop tables and recreate.");
         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
         onCreate(db);
      }
   }
}